<script setup>
import QrAuth from '@/components/QrAuth/QrAuth.vue'
import useSettingsStore from '@/store/modules/settings'
import { handleThemeStyle } from '@/utils/theme'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import VXETable from 'vxe-table'

onMounted(() => {
  nextTick(() => {
    // 初始化主题样式
    handleThemeStyle(useSettingsStore().theme)
  })
})
const settings = useSettingsStore()
const prefersColorScheme = window.matchMedia('(prefers-color-scheme: dark)')

watch(() => settings.colorScheme, (val) => {
  if (val === '') {
    prefersColorScheme.addEventListener('change', updateTheme)
  }
  else {
    prefersColorScheme.removeEventListener('change', updateTheme)
  }
}, {
  immediate: true,
})
watch(() => settings.colorScheme, updateTheme, {
  immediate: true,
})

function updateTheme() {
  let colorScheme = settings.colorScheme
  if (colorScheme === '') {
    colorScheme = prefersColorScheme.matches ? 'dark' : 'light'
  }
  settings.updateCurrentTheme(colorScheme)
  switch (colorScheme) {
    case 'light':
      VXETable.setConfig({
        theme: 'default',
      })
      document.documentElement.classList.remove('dark')
      break
    case 'dark':
      document.documentElement.classList.add('dark')
      VXETable.setConfig({
        theme: 'dark',
      })
      break
  }
}
</script>

<template>
  <el-config-provider
    :locale="zhCn"
    :button="{
      autoInsertSpace: true,
    }"
  >
    <router-view />
    <QrAuth />
  </el-config-provider>
</template>
